// Global variables
let widgets = new Map();
let currentLanguage = 'en';
let currentUser = null;
let sessionId = null;

// Initialize the application
document.addEventListener('DOMContentLoaded', function() {
    checkAuthStatus();
    updateLanguage();
    initializeWidgetManager();
});

// Global widget manager for handling widget actions
function initializeWidgetManager() {
    window.widgetManager = {
        async executeWidgetAction(widgetId, action, params = {}) {
            const widget = widgets.get(widgetId);
            if (!widget) {
                console.error('Widget not found:', widgetId);
                return;
            }

            const widgetElement = document.querySelector(`[data-widget-id="${widgetId}"]`);
            if (!widgetElement) {
                console.error('Widget element not found:', widgetId);
                return;
            }

            // Get widget type from element
            const widgetType = widgetElement.classList.contains('todo-widget') ? 'todo' : 'calendar';
            
            try {
                switch (action) {
                    case 'changeView':
                        await this.handleCalendarAction(widgetId, 'changeCalendarView', params);
                        break;
                    case 'showAddEventModal':
                        await this.handleCalendarAction(widgetId, 'showAddEventModal', params);
                        break;
                    case 'hideAddEventModal':
                        await this.handleCalendarAction(widgetId, 'hideAddEventModal', params);
                        break;
                    case 'handleAddEvent':
                        await this.handleCalendarAction(widgetId, 'handleAddEvent', params);
                        break;
                    case 'deleteEvent':
                        await this.handleCalendarAction(widgetId, 'deleteEventFromWidget', params);
                        break;
                    case 'showAddTodoModal':
                        await this.handleTodoAction(widgetId, 'showAddTodoModal', params);
                        break;
                    case 'hideAddTodoModal':
                        await this.handleTodoAction(widgetId, 'hideAddTodoModal', params);
                        break;
                    case 'handleAddTodo':
                        await this.handleTodoAction(widgetId, 'handleAddTodo', params);
                        break;
                    case 'toggleTodo':
                        await this.handleTodoAction(widgetId, 'toggleTodoFromWidget', params);
                        break;
                    case 'deleteTodo':
                        await this.handleTodoAction(widgetId, 'deleteTodoFromWidget', params);
                        break;
                    default:
                        console.error('Unknown action:', action);
                }
            } catch (error) {
                console.error('Error executing widget action:', error);
            }
        },

        async handleCalendarAction(widgetId, method, params) {
            try {
                const response = await fetch(`/api/widgets/${widgetId}/actions/${method}`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ data: params })
                });
                
                if (response.ok) {
                    // For actions that need UI refresh, the widget will handle it internally
                    await refreshWidget(widgetId);
                } else {
                    const result = await response.json();
                    alert(result.error);
                }
            } catch (error) {
                console.error('Error in calendar action:', error);
                alert('Error performing calendar action');
            }
        },

        async handleTodoAction(widgetId, method, params) {
            try {
                const response = await fetch(`/api/widgets/${widgetId}/actions/${method}`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ data: params })
                });
                
                if (response.ok) {
                    // For actions that need UI refresh, the widget will handle it internally
                    await refreshWidget(widgetId);
                } else {
                    const result = await response.json();
                    alert(result.error);
                }
            } catch (error) {
                console.error('Error in todo action:', error);
                alert('Error performing todo action');
            }
        }
    };
}

// Language management
function changeLanguage(lang) {
    currentLanguage = lang;
    localStorage.setItem('language', lang);
    updateLanguage();
    
    // Update server language
    fetch('/api/language', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ lang })
    });
}

function updateLanguage() {
    const savedLang = localStorage.getItem('language');
    if (savedLang) {
        currentLanguage = savedLang;
        document.getElementById('languageSelect').value = savedLang;
    }
    
    // Update all text with i18n attributes
    document.querySelectorAll('[data-i18n]').forEach(element => {
        const key = element.getAttribute('data-i18n');
        element.textContent = getTranslation(key);
    });
}

function getTranslation(key) {
    const translations = {
        'en': {
            'app.addWidget': 'Add Widget',
            'app.noWidgets': 'No widgets yet',
            'app.clickToAddWidget': 'Click "Add Widget" to get started',
            'app.addFirstWidget': 'Add Your First Widget',
            'auth.login': 'Login',
            'auth.logout': 'Logout',
            'auth.username': 'Username',
            'auth.password': 'Password',
            'auth.role': 'Role',
            'admin.userManagement': 'User Management',
            'admin.addUser': 'Add User',
            'admin.addNewUser': 'Add New User',
            'common.cancel': 'Cancel'
        },
        'zh': {
            'app.addWidget': '添加组件',
            'app.noWidgets': '暂无组件',
            'app.clickToAddWidget': '点击"添加组件"开始使用',
            'app.addFirstWidget': '添加您的第一个组件',
            'auth.login': '登录',
            'auth.logout': '登出',
            'auth.username': '用户名',
            'auth.password': '密码',
            'auth.role': '角色',
            'admin.userManagement': '用户管理',
            'admin.addUser': '添加用户',
            'admin.addNewUser': '添加新用户',
            'common.cancel': '取消'
        }
    };
    
    return translations[currentLanguage][key] || key;
}

// Authentication functions
async function checkAuthStatus() {
    try {
        const response = await fetch('/api/auth/me');
        if (response.ok) {
            const data = await response.json();
            currentUser = data.user;
            sessionId = getCookie('sessionId');
            updateUIForAuth();
            loadStoredWidgets();
        } else {
            updateUIForUnauth();
        }
    } catch (error) {
        updateUIForUnauth();
    }
}

function updateUIForAuth() {
    document.getElementById('userInfo').style.display = 'flex';
    document.getElementById('loginBtn').style.display = 'none';
    document.getElementById('addWidgetBtn').style.display = 'flex';
    document.getElementById('username').textContent = currentUser.username;
    
    // Add admin menu if user is admin
    const userMenu = document.getElementById('userMenu');
    const existingAdminMenu = userMenu.querySelector('.admin-menu-item');
    if (currentUser.role === 'admin' && !existingAdminMenu) {
        const adminMenuItem = document.createElement('button');
        adminMenuItem.className = 'admin-menu-item';
        adminMenuItem.innerHTML = '<i class="fas fa-users-cog"></i><span>User Management</span>';
        adminMenuItem.onclick = showUserManagementModal;
        userMenu.appendChild(adminMenuItem);
    }
}

function updateUIForUnauth() {
    document.getElementById('userInfo').style.display = 'none';
    document.getElementById('loginBtn').style.display = 'flex';
    document.getElementById('addWidgetBtn').style.display = 'none';
    currentUser = null;
    sessionId = null;
    clearWidgets();
}

function showLoginModal() {
    document.getElementById('loginModal').classList.add('active');
    document.getElementById('overlay').classList.add('active');
}

function hideLoginModal() {
    document.getElementById('loginModal').classList.remove('active');
    document.getElementById('overlay').classList.remove('active');
    document.getElementById('loginForm').reset();
}

async function handleLogin(event) {
    event.preventDefault();
    
    const username = document.getElementById('loginUsername').value;
    const password = document.getElementById('loginPassword').value;
    
    try {
        const response = await fetch('/api/auth/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ username, password })
        });
        
        if (response.ok) {
            const data = await response.json();
            currentUser = data.user;
            sessionId = data.sessionId;
            // Cookie is now set by server, no need to set it manually
            updateUIForAuth();
            loadStoredWidgets();
            hideLoginModal();
        } else {
            const error = await response.json();
            alert('Login failed: ' + error.error);
        }
    } catch (error) {
        alert('Login failed: ' + error.message);
    }
}

async function logout() {
    try {
        await fetch('/api/auth/logout', { method: 'POST' });
        // Cookie is now cleared by server, no need to clear it manually
        currentUser = null;
        sessionId = null;
        updateUIForUnauth();
        toggleUserMenu();
    } catch (error) {
        console.error('Logout failed:', error);
    }
}

function toggleUserMenu() {
    const userMenu = document.getElementById('userMenu');
    userMenu.classList.toggle('active');
}

// Admin user management functions
async function showUserManagementModal() {
    if (currentUser.role !== 'admin') return;
    
    document.getElementById('userManagementModal').classList.add('active');
    document.getElementById('overlay').classList.add('active');
    loadUsers();
    toggleUserMenu();
}

function hideUserManagementModal() {
    document.getElementById('userManagementModal').classList.remove('active');
    document.getElementById('overlay').classList.remove('active');
    hideAddUserForm();
}

async function loadUsers() {
    try {
        const response = await fetch('/api/users', {
            headers: { 'Authorization': `Bearer ${sessionId}` }
        });
        
        if (response.ok) {
            const users = await response.json();
            displayUsers(users);
        }
    } catch (error) {
        console.error('Failed to load users:', error);
    }
}

function displayUsers(users) {
    const userList = document.getElementById('userList');
    userList.innerHTML = '';
    
    users.forEach(user => {
        const userItem = document.createElement('div');
        userItem.className = 'user-item';
        userItem.innerHTML = `
            <div class="user-item-info">
                <span class="user-item-username">${user.username}</span>
                <span class="user-item-role ${user.role}">${user.role}</span>
            </div>
            <div class="user-item-actions">
                <button class="delete" onclick="deleteUser(${user.id})">Delete</button>
            </div>
        `;
        userList.appendChild(userItem);
    });
}

function showAddUserForm() {
    document.getElementById('addUserForm').style.display = 'block';
}

function hideAddUserForm() {
    document.getElementById('addUserForm').style.display = 'none';
    document.getElementById('addUserFormElement').reset();
}

async function handleAddUser(event) {
    event.preventDefault();
    
    const username = document.getElementById('newUsername').value;
    const password = document.getElementById('newPassword').value;
    const role = document.getElementById('newUserRole').value;
    
    try {
        const response = await fetch('/api/users', {
            method: 'POST',
            headers: { 
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${sessionId}`
            },
            body: JSON.stringify({ username, password, role })
        });
        
        if (response.ok) {
            loadUsers();
            hideAddUserForm();
        } else {
            const error = await response.json();
            alert('Failed to add user: ' + error.error);
        }
    } catch (error) {
        alert('Failed to add user: ' + error.message);
    }
}

async function deleteUser(userId) {
    if (!confirm('Are you sure you want to delete this user?')) return;
    
    try {
        const response = await fetch(`/api/users/${userId}`, {
            method: 'DELETE',
            headers: { 'Authorization': `Bearer ${sessionId}` }
        });
        
        if (response.ok) {
            loadUsers();
        } else {
            const error = await response.json();
            alert('Failed to delete user: ' + error.error);
        }
    } catch (error) {
        alert('Failed to delete user: ' + error.message);
    }
}

// Cookie helper functions
function setCookie(name, value, days) {
    const expires = new Date();
    expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
    document.cookie = `${name}=${value};expires=${expires.toUTCString()};path=/`;
}

function getCookie(name) {
    const nameEQ = name + "=";
    const ca = document.cookie.split(';');
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function deleteCookie(name) {
    document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 UTC;path=/`;
}

// Widget panel management
function toggleWidgetPanel() {
    const panel = document.getElementById('widgetPanel');
    const overlay = document.querySelector('.overlay');
    
    if (panel.classList.contains('active')) {
        panel.classList.remove('active');
        overlay.classList.remove('active');
    } else {
        panel.classList.add('active');
        overlay.classList.add('active');
        loadAvailableWidgets();
    }
}

// Load available widgets dynamically
async function loadAvailableWidgets() {
    try {
        const response = await fetch('/api/widgets');
        const widgets = await response.json();
        
        const widgetTypesContainer = document.getElementById('widgetTypes');
        widgetTypesContainer.innerHTML = '';
        
        widgets.forEach(widget => {
            const widgetCard = document.createElement('div');
            widgetCard.className = 'widget-type-card';
            widgetCard.setAttribute('data-type', widget.name);
            widgetCard.onclick = () => selectWidgetType(widget.name);
            
            widgetCard.innerHTML = `
                <div class="widget-icon">
                    <i class="fas ${widget.icon || 'fa-cube'}"></i>
                </div>
                <div class="widget-info">
                    <h4>${widget.displayName || widget.name}</h4>
                    <p>${widget.description || 'No description available'}</p>
                </div>
            `;
            
            widgetTypesContainer.appendChild(widgetCard);
        });
    } catch (error) {
        console.error('Error loading available widgets:', error);
        const widgetTypesContainer = document.getElementById('widgetTypes');
        widgetTypesContainer.innerHTML = '<p>Error loading widgets</p>';
    }
}

function selectWidgetType(type) {
    // Remove previous selection
    document.querySelectorAll('.widget-type-card').forEach(card => {
        card.classList.remove('selected');
    });
    
    // Select current type
    document.querySelector(`[data-type="${type}"]`).classList.add('selected');
    
    // Show configuration section
    const configSection = document.getElementById('configSection');
    const configHelp = document.getElementById('configHelp');
    
    configSection.style.display = 'block';
    
    // Show configuration help based on widget type
    let helpHtml = '';
    if (type === 'todo') {
        helpHtml = `
            <div class="config-example">
                <h5><i class="fas fa-info-circle"></i> Todo Widget Configuration</h5>
                <div class="config-fields">
                    <div class="field">
                        <strong>language</strong>
                        <div class="field-example"><code>"en" or "zh"</code></div>
                    </div>
                    <div class="field">
                        <strong>todos</strong>
                        <div class="field-example"><code>Array of todo objects</code></div>
                    </div>
                </div>
                <div class="config-sample">
                    <strong>Example:</strong>
                    <pre>{
  "language": "en",
  "todos": [
    {
      "text": "Welcome to Todo Widget!",
      "priority": "medium",
      "completed": false
    }
  ]
}</pre>
                </div>
            </div>
        `;
    } else if (type === 'calendar') {
        helpHtml = `
            <div class="config-example">
                <h5><i class="fas fa-info-circle"></i> Calendar Widget Configuration</h5>
                <div class="config-fields">
                    <div class="field">
                        <strong>language</strong>
                        <div class="field-example"><code>"en" or "zh"</code></div>
                    </div>
                    <div class="field">
                        <strong>events</strong>
                        <div class="field-example"><code>Array of event objects</code></div>
                    </div>
                </div>
                <div class="config-sample">
                    <strong>Example:</strong>
                    <pre>{
  "language": "en",
  "events": [
    {
      "title": "Welcome to Calendar Widget!",
      "date": "${new Date().toISOString()}",
      "type": "meeting",
      "description": "Get started with your calendar"
    }
  ]
}</pre>
                </div>
            </div>
        `;
    }
    
    configHelp.innerHTML = helpHtml;
}

async function createSelectedWidget() {
    const selectedCard = document.querySelector('.widget-type-card.selected');
    if (!selectedCard) {
        alert('Please select a widget type');
        return;
    }
    
    const widgetType = selectedCard.getAttribute('data-type');
    const configText = document.getElementById('widgetConfig').value;
    
    let config = { language: currentLanguage };
    if (configText.trim()) {
        try {
            config = { ...config, ...JSON.parse(configText) };
        } catch (error) {
            alert('Invalid JSON configuration');
            return;
        }
    }
    
    try {
        const response = await fetch(`/api/widgets/${widgetType}/instantiate`, {
            method: 'POST',
            headers: { 
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${sessionId}`
            },
            body: JSON.stringify({ config })
        });
        
        const result = await response.json();
        
        if (response.ok) {
            await loadWidgetTemplate(result.id, widgetType);
            toggleWidgetPanel();
        } else {
            alert(result.error);
        }
    } catch (error) {
        console.error('Error creating widget:', error);
        alert('Error creating widget');
    }
}

async function loadWidgetTemplate(widgetId, widgetType) {
    try {
        const response = await fetch(`/api/widgets/${widgetId}/template`, {
            headers: { 'Authorization': `Bearer ${sessionId}` }
        });
        const result = await response.json();
        
        if (response.ok) {
            addWidgetToGrid(widgetId, result.template);
            widgets.set(widgetId, { type: widgetType });
        } else {
            console.error('Error loading widget template:', result.error);
        }
    } catch (error) {
        console.error('Error loading widget template:', error);
    }
}

function addWidgetToGrid(widgetId, template) {
    const mainGrid = document.getElementById('mainGrid');
    
    // Remove empty state if it exists
    const emptyState = mainGrid.querySelector('.empty-state');
    if (emptyState) {
        emptyState.remove();
    }
    
    // Create widget card
    const widgetCard = document.createElement('div');
    widgetCard.className = 'widget-card';
    widgetCard.setAttribute('data-widget-id', widgetId);
    
    widgetCard.innerHTML = `
        <div class="widget-header">
            <div class="widget-title">
                <i class="fas fa-cube"></i>
                <h3>Widget</h3>
            </div>
            <div class="widget-actions">
                <button class="widget-btn" onclick="refreshWidget('${widgetId}')" title="Refresh">
                    <i class="fas fa-sync"></i>
                </button>
                <button class="widget-btn delete" onclick="deleteWidget('${widgetId}')" title="Delete">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        </div>
        <div class="widget-content" id="widget-content-${widgetId}">
            ${template}
        </div>
    `;
    
    mainGrid.appendChild(widgetCard);
}

async function deleteWidget(widgetId) {
    if (!confirm('Are you sure you want to delete this widget?')) {
        return;
    }
    
    try {
        const response = await fetch(`/api/widgets/${widgetId}`, {
            method: 'DELETE'
        });
        
        if (response.ok) {
            const widgetCard = document.querySelector(`[data-widget-id="${widgetId}"]`);
            if (widgetCard) {
                widgetCard.remove();
            }
            widgets.delete(widgetId);
            
            // Show empty state if no widgets left
            const mainGrid = document.getElementById('mainGrid');
            if (mainGrid.children.length === 0) {
                showEmptyState();
            }
        } else {
            alert('Error deleting widget');
        }
    } catch (error) {
        console.error('Error deleting widget:', error);
        alert('Error deleting widget');
    }
}

async function refreshWidget(widgetId) {
    try {
        const response = await fetch(`/api/widgets/${widgetId}/template`);
        const result = await response.json();
        
        if (response.ok) {
            const widgetContent = document.getElementById(`widget-content-${widgetId}`);
            if (widgetContent) {
                widgetContent.innerHTML = result.template;
            }
        }
    } catch (error) {
        console.error('Error refreshing widget:', error);
    }
}

// All widget handling logic is now inside the widget components

// Utility functions
function showEmptyState() {
    const mainGrid = document.getElementById('mainGrid');
    mainGrid.innerHTML = `
        <div class="empty-state">
            <i class="fas fa-cube"></i>
            <h2 data-i18n="app.noWidgets">No widgets yet</h2>
            <p data-i18n="app.clickToAddWidget">Click "Add Widget" to get started</p>
            <button class="add-widget-btn" onclick="toggleWidgetPanel()">
                <i class="fas fa-plus"></i>
                <span data-i18n="app.addFirstWidget">Add Your First Widget</span>
            </button>
        </div>
    `;
    updateLanguage();
}

async function loadStoredWidgets() {
    if (!currentUser) {
        showEmptyState();
        return;
    }
    
    try {
        const response = await fetch('/api/widgets/user', {
            headers: { 'Authorization': `Bearer ${sessionId}` }
        });
        
        if (response.ok) {
            const userWidgets = await response.json();
            
            if (userWidgets.length === 0) {
                showEmptyState();
            } else {
                // Load each widget template
                for (const widget of userWidgets) {
                    await loadWidgetTemplate(widget.id, widget.name);
                }
            }
        } else {
            showEmptyState();
        }
    } catch (error) {
        console.error('Error loading stored widgets:', error);
        showEmptyState();
    }
}

// Add DELETE endpoint support (add this to your server)
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        const panel = document.getElementById('widgetPanel');
        if (panel.classList.contains('active')) {
            toggleWidgetPanel();
        }
    }
});